<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户资源
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-switch v-model="query.activeStatus" class="handle-switch mr40" @change="func_switch_load"
                    placeholder="隐藏状态" active-value="1" inactive-value="0" active-text="已删除" inactive-text="全部资源" >
                </el-switch>
                <el-input v-model="query.keyword" placeholder="资源名" class="handle-input mr10"/>
                <el-button type="primary" icon="el-icon-search" @click="func_handleSearch">搜索</el-button>
                <el-dropdown style="margin-left:15px">
                    <el-button type="warning">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <template #dropdown>
                    <el-dropdown-menu >
                        <el-dropdown-item icon="el-icon-edit" @click="func_handleAddBut">新建</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-delete" @click="func_handleDelBut">删除</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-refresh-right" @click="func_handleRecyclingBut">恢复</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-circle-check" @click="func_handleViewBut">可见</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-circle-close" @click="func_handleUnViewBut">不可见</el-dropdown-item>
                    </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <el-table v-loading="isLoading" :data="resouseTableData" class="table" ref="multipleTable" border lazy 
            element-loading-background = "rgba(255, 255, 255, .5)" element-loading-text = "加载中，请稍后..." element-loading-spinner = "el-icon-loading"
            row-key="id" :load="func_table_lazy_load" :tree-props="{children: 'resouseChildren', hasChildren: 'hasChildren'}"
            @selection-change="(selections)=>{func_handleSelectionChange(selections,'true')}"
            @select-all="(selections)=>{func_handleSelectionAll(selections,'true')}"
            header-cell-class-name="table-header" default-expand-all >
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column prop="id" label="ID" align="center"/>
                <el-table-column prop="sid" label="识别码" v-if="false">
                    <template #default="scope">
                        {{scope.row.sid}} {{scope.row.hidden}} {{scope.row.children}}
                    </template>
                </el-table-column>
                <el-table-column prop="icon" label="资源图标" align="center"/>
                <el-table-column prop="title" label="资源标题" align="center">
                    <template #default="scope">
                        <el-button type="text" icon="el-icon-s-unfold" @click="func_handleDrawerOpen(scope.$index, scope.row)">{{scope.row.title}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="资源名称" align="center"/>
                <el-table-column prop="router" label="资源路径" align="center"/>
                <el-table-column prop="sort" label="排序" align="center"/>
                <el-table-column prop="strHidden" label="可见状态" align="center"/>
                <el-table-column label="数据状态" align="center">
                    <template #default="scope">
                        <p v-if="scope.row.isDel"><el-tag size="small" type="danger" effect="dark">已删除</el-tag></p>
                        <p v-if="!scope.row.isDel"><el-tag size="small" type="success" effect="dark">正常</el-tag></p>
                    </template>
                </el-table-column>
                <el-table-column prop="strCreateTime" label="建立时间" align="center"/>
                <el-table-column label="操作" width="180" align="center">
                    <template #default="scope">
                        <p v-if="scope.row.isDel">
                            <el-button type="text" icon="el-icon-edit" class="red" @click="func_handleRecycling(scope.$index, scope.row)">恢复</el-button>
                        </p>
                        <p v-if="!scope.row.isDel">
                            <el-button type="text" icon="el-icon-edit" @click="func_handleEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button type="text" icon="el-icon-delete" class="red" @click="func_handleDelete(scope.$index, scope.row)">删除</el-button>
                        </p>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @size-change="func_handleSizeChange" @current-change="func_handlePageChange"
                background layout="total, sizes, prev, pager, next," 
                        :current-page="query.pageNum"
                        :page-sizes=[10,50,100]
                        :page-size="query.pageSize"
                        :total="total" >
                </el-pagination>
            </div>
        </div>
        <el-drawer title="详细信息" v-model="view_resouseDrawer" direction="rtl" size="55%">
            <el-tabs v-model="view_activeName" type="border-card" @tab-click="func_drawer_tabsClick" style="height:65%;overflow-y:auto;overflow-x:hidden">
                <!-- #1. 资源说明 --------------------------------------------------------------------------------------------------- -->
                <el-tab-pane label="资源说明" name="resouse1" :key="'resouse1'" >
                    <el-card class="box-card">
                        <el-descriptions title="基础信息" direction="vertical" :column="3" border>
                            <el-descriptions-item label="ID" :span="3">{{resouseDrawerForm.id}}</el-descriptions-item>
                            <el-descriptions-item label="识别码" :span="3">{{resouseDrawerForm.sid}}</el-descriptions-item>
                            <el-descriptions-item label="资源名称" :span="3">{{resouseDrawerForm.name}}</el-descriptions-item>
                            <el-descriptions-item label="隐藏状态" :span="3">{{resouseDrawerForm.strChecked}}</el-descriptions-item>
                            <el-descriptions-item label="创建时间" :span="3">{{resouseDrawerForm.strCreateTime}}</el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-tab-pane>
                <el-tab-pane label="资源说明2" name="resouse2" :key="'resouse2'" />
            </el-tabs>
        </el-drawer>
        <!-- 编辑弹出框 -->
        <el-dialog v-model="view_editVisible" >
            <div class="handle-box">
                <span><h3>{{resouseDrawerFormHeadTitle}}</h3></span>
            </div>
            <el-card class="box-card">
            <el-form label-width="formLabelWidth">
                <el-form-item label="资源图标" :label-width="formLabelWidth">
                    <el-input v-model="resouseDrawerForm.icon" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="资源名称" :label-width="formLabelWidth">
                    <el-input v-model="resouseDrawerForm.name" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="资源展示标题" :label-width="formLabelWidth">
                    <el-input v-model="resouseDrawerForm.title" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="路由" :label-width="formLabelWidth">
                    <el-input v-model="resouseDrawerForm.router" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="路径" :label-width="formLabelWidth">
                    <el-input v-model="resouseDrawerForm.path" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="资源级别" :label-width="formLabelWidth">
                    <el-switch v-model="levelShowSwitch" class="handle-switch mr40" 
                        placeholder="资源级别" active-value=1 inactive-value=0 active-text="子资源" inactive-text="主资源" @change="func_setLevelEditView">
                    </el-switch>
                    <!-- <el-select v-model="resouseDrawerForm.level" v-show="view_levelShow" placeholder="资源级别" > -->
                        <!-- <el-option label="子资源" value=1 :key="-1"></el-option> -->
                        <!-- <el-option v-for="(item,i) in dialog_level_Options" :key="i" :label="item.label" :value="item.value" /> -->
                    <!-- </el-select> -->
                </el-form-item>
                <el-form-item label="上一级资源" :label-width="formLabelWidth" v-show="view_levelShow">
                    <el-input v-model="resouseDrawerForm.str_level" autocomplete="off" :readonly=true />
                </el-form-item>
                <el-form-item label="层级" :label-width="formLabelWidth">
                    {{resouseDrawerForm.level}}
                </el-form-item>
                <el-form-item label="排序" :label-width="formLabelWidth">
                    <el-select v-model="resouseDrawerForm.sort" placeholder="资源排序">
                        <el-option label="1" value="1"></el-option>
                        <el-option label="2" value="2"></el-option>
                        <el-option label="3" value="3"></el-option>
                        <el-option label="4" value="4"></el-option>
                        <el-option label="5" value="5"></el-option>
                        <el-option label="6" value="6"></el-option>
                        <el-option label="7" value="7"></el-option>
                        <el-option label="8" value="8"></el-option>
                        <el-option label="9" value="9"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否普通用户可见" :label-width="formLabelWidth">
                    <el-switch v-model="resouseDrawerForm.hidden" class="handle-switch mr40" 
                        placeholder="是否隐藏" active-value="1" inactive-value="0" active-text="隐藏" inactive-text="可见">
                    </el-switch>
                    <!-- <el-select v-model="resouseDrawerForm.hidden" placeholder="是否可见">
                        <el-option label="是" value="1"></el-option>
                        <el-option label="否" value="0"></el-option>
                    </el-select> -->
                </el-form-item>
                <el-form-item label="说明" :label-width="formLabelWidth">
                    <el-input v-model="resouseDrawerForm.note" autocomplete="off"/>
                </el-form-item>
            </el-form></el-card>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="view_editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="func_dialog_saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog title="选择对话框" v-model="view_dialog_optionsVisible" >
            <el-table :data="dialog_optionTableData" border class="table" header-cell-class-name="table-header" @row-click="func_dialog_chooseOptionData">
                <el-table-column prop="sid" label="sid" width="150"/>
                <el-table-column prop="path" label="路径" width="200"/>
                <el-table-column prop="name" label="名称"/>
                <el-table-column prop="level" label="层级"/>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { fetchResouseData, fetchOptionResouseData, editResouser, batchDelResouser, batchRecResouser,
batchHiddenResouser, batchUnHiddenResouser } from "../../api/uc";
import { defineComponent } from 'vue';

export default defineComponent({
    name: "resousetable",
    setup() {
        let ERROR_CHOOSE_DEL_RESOUSE_EMPTY = "请选择一个要删除的菜单资源";
        let ERROR_CHOOSE_REC_RESOUSE_EMPTY = "请选择一个要恢复的菜单资源";
        let ERROR_CHOOSE_VIEW_RESOUSE_EMPTY = "请选择一个菜单资源";
        let SUCCMESS_DIALOG_MESSAGE = "操作成功";
        let FAILD_DIALOG_MESSAGE = "操作失败";
        // 表单loading: true,
        const isLoading = ref(true);
        // 表单输入框前长度
        const formLabelWidth = ref("170px");
        let resouseDrawerFormHeadTitle = ref("");
        let add_flg = ref(true);
        // 外置列表总页数
        const total = ref(0);
        // 资源查询条件
        const query = reactive({
            keyword: "",
            pageNum: 1,
            pageSize: 10,
            activeStatus: 0,
            level: 0,
        });
        // 资源数据表
        const resouseTableData = ref([{
            id: 0,
            sid: '',
            icon: '',
            title: '',
            name: '',
            router: '',
            strCreateTime: '',
            orderLevel: 0,
            hidden: 0,
            isDel: false,
            strHidden: '',
            children: [{}],
        }]);
        // 公共 数据表多选临时存储
        let multipleTable = ref([]);
        let multipleSelectData = reactive([]);
        /**
         * @name 公共 列表内选择数据
         * @description 勾选的回调函数，返回全部勾选值
         */
        const func_handleSelectionChange = (selections,param) => {
            multipleSelectData = selections;
        };
        /**
         * @name 公共 列表内全选数据
         * @description 勾选的回调函数，返回全部勾选值
         */
        const func_handleSelectionAll = (selections,param) => {
            multipleSelectData = selections;
        };
        /**
         * @name 获取主表格数据
         */
        const func_getData = () => {
            resouseTableData.value= [];
            var t= setTimeout(function() {
                fetchResouseData(query).then((res) => {
                    resouseTableData.value = res.data.data.list;
                    total.value = res.data.data.total;
                    isLoading.value = false;
                }).catch(() => { isLoading.value = false;});
            },1000);
        };
        func_getData();
        /**
         * @name 查询操作
         */
        const func_handleSearch = () => {
            isLoading.value = true;
            query.pageNum = 1;
            func_getData();
        };
        const func_switch_load = () => {
            isLoading.value = true;
            query.pageNum = 1;
            func_getData();
        };
        /**
         * @name 添加操作
         */
        const func_handleAddBut = (but,event) => {
            resouseDrawerFormHeadTitle.value = "新建菜单资源";
            Object.keys(resouseDrawerForm).forEach((item) => {
                resouseDrawerForm[item] = '';
            });
            resouseDrawerForm.id = 0;
            add_flg = true;
            view_editVisible.value = true;
        };
        /**
         * 标签内方法
         * @name 资源批量删除方法
         * @description 主按钮下拉的批量删除操作
         */
        const func_handleDelBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_DEL_RESOUSE_EMPTY);
                return;
            }
            let _v = multipleSelectData.map((item) => item.id);
            func_del_data(_v);
        };
        /**
         * 标签内方法
         * @name 资源批量恢复方法
         * @description 主按钮下拉的批量恢复操作
         */
        const func_handleRecyclingBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_REC_RESOUSE_EMPTY);
                return;
            }
            let _v = multipleSelectData.map((item) => item.id);
            func_rec_data(_v);
        };
        /**
         * 标签内方法
         * @name 资源批量设置普通用户可见方法
         * @description 主按钮下拉的批量设置普通用户是否可见操作
         */
        const func_handleViewBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_VIEW_RESOUSE_EMPTY);
                return;
            }
            let _v = multipleSelectData.map((item) => item.id);
            func_view_data(_v);
        };
        /**
         * 标签内方法
         * @name 资源批量设置普通用户不可见方法
         * @description 主按钮下拉的批量设置普通用户是否可见操作
         */
        const func_handleUnViewBut = (but,event) => {
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_VIEW_RESOUSE_EMPTY);
                return;
            }
            let _v = multipleSelectData.map((item) => item.id);
            func_unview_data(_v);
        };
        /**
         * @name 分页导航
         */
        const func_handlePageChange = (val) => {
            isLoading.value = true;
            query.pageNum = val;
            func_getData();
        };
        /**
         * @name 分页数量查询
         */
        const func_handleSizeChange = (val) => {
            isLoading.value = true;
            query.pageNum = 1;
            query.pageSize = val;
            func_getData();
        };
        /**
         * @name 表格行内编辑操作
         */
        let idx = -1;
        const func_handleEdit = (index, row) => {
            idx = index;
            Object.keys(resouseDrawerForm).forEach((item) => {
                resouseDrawerForm[item] = row[item];
            });
            levelShowSwitch.value = resouseDrawerForm['parentSid'];
            add_flg = false;
            view_editVisible.value = true;
        };
        /**
         * @name 对话框保存数据
         */
        const func_dialog_saveEdit = () => {
            editResouser(resouseDrawerForm).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    if(add_flg) {
                        ElMessage.success({ type: 'success', duration: 3000, message: `添加成功` });
                    } else {
                        ElMessage.success({ type: 'success', duration: 3000, message: `修改第 ${idx + 1} 行成功` });
                    }
                    view_editVisible.value = false; // 关闭对话框
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 表格行内删除操作
         */
        const func_handleDelete = (index, row) => {
            if(row['hasChildren']){
                // 二次确认删除
                ElMessageBox.confirm("数据包含子项目，确定要全部删除吗？", "提示", {type: "warning",}).then(() => {
                    let _v = [row['id']];
                    func_del_data(_v);
                }).catch(() => {});
            } else {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {type: "warning",}).then(() => {
                    let _v = [row['id']];
                    func_del_data(_v);
                }).catch(() => {});
            }
        };
        /**
         * @name 表格行内回收操作
         */
        const func_handleRecycling = (index, row) => {
            let _v = [row['id']];
            func_rec_data(_v);
        };
        /**
         * @name 删除ID的数据
         */
        const func_del_data = (_data) => {
            batchDelResouser(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 回收ID的数据
         */
        const func_rec_data = (_data) => {
            batchRecResouser(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 普通用户可见的数据
         */
        const func_view_data = (_data) => {
            batchUnHiddenResouser(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * @name 普通用户不可见的数据
         */
        const func_unview_data = (_data) => {
            batchHiddenResouser(_data).then((res) => {
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    isLoading.value = true;
                    func_getData(); // 刷新数据
                }
            }).catch(() => {});
        };
        /**
         * ----------------------------------------------------抽屉内方法-------------------------------------------------*/
        // 抽屉展示区分
        const view_resouseDrawer = ref(false);
        // 抽屉内标签页区分
        const view_activeName = ref();
        const view_levelShow = ref(false);
        const resouseDrawerForm = reactive({
            id: 0,
            sid: '',
            parentSid: '',
            level: 0,
            str_level: '',
            icon: '',
            title: '',
            name: '',
            router: '',
            path: '',
            note: '',
            strCreateTime: '',
            orderLevel: 0,
            sort: 0,
            hidden: 0,
            strHidden: ''
        });
        /**
         * 打开弹出层
         */
        const func_handleDrawerOpen = (index, row) => {
            Object.keys(row).forEach((item) => {
                resouseDrawerForm[item] = row[item];
            });
            view_resouseDrawer.value=true;
            view_activeName.value = "resouse1";
        };
        const func_handleDrawerClose = (done) => {
            this.$confirm('确认关闭？').then(_ => {
                done();
            }).catch(_ => {});
        };
        /**
         * Drawer 标签内方法
         * @name 标签切换
         */
        const func_drawer_tabsClick = (tab,event)=> {
            // ElMessage.success("切换成功");
        };
        /**
         * ----------------------------------------------------对话框方法-------------------------------------------------*/
        let levelShowSwitch = ref(1);
        // let dialog_level_Options = ref([]);
        const view_dialog_optionsVisible = ref(false);
        // 表格编辑时弹窗和保存
        const view_editVisible = ref(false);
        /**
         * 读取资源的下拉表数据
         */
        const func_setLevelEditView =() => {
            if (levelShowSwitch.value == 1) {
                view_levelShow.value = true;
                // 读取资源列表目录树
                fetchOptionResouseData(query).then((res) => {
                    dialog_optionTableData.value = res.data.data.list;
                    view_dialog_optionsVisible.value = true;
                });
            } else {
                resouseDrawerForm.level = 0;
                resouseDrawerForm.parentSid = '0';
                view_levelShow.value = false;
            }
        };
        const func_dialog_chooseOptionData =(row, event, column) =>{
            resouseDrawerForm.level = row['level']+1;
            resouseDrawerForm.str_level = row['name'];
            resouseDrawerForm.parentSid = row['sid'];
            view_dialog_optionsVisible.value = false;
        }
        const func_table_lazy_load = (tree, treeNode, resolve) => {
            setTimeout(() => {resolve(tree['children'])}, 1000);
        };
        const dialog_optionTableData = ref([{
            sid: '',
            name: '',
            path: '',
            level: 0,
        }]);
        /**
         * ----------------------------------------------------初始化页面对象---------------------------------------------*/
        return {
            isLoading, query, total,
            formLabelWidth, add_flg,
            resouseTableData,
            multipleTable, multipleSelectData,
            func_handleSelectionAll,
            func_handleSelectionChange,
            resouseDrawerFormHeadTitle,
            resouseDrawerForm,
            levelShowSwitch,
            view_resouseDrawer,
            view_activeName,
            view_editVisible,
            view_dialog_optionsVisible,
            dialog_optionTableData,
            // dialog_level_Options,
            view_levelShow,
            func_getData,
            func_handleSearch,
            func_switch_load,
            func_handleAddBut,
            func_handleDelBut,
            func_handleRecyclingBut,
            func_handleViewBut,
            func_handleUnViewBut,
            func_handlePageChange,
            func_handleSizeChange,
            func_handleDelete,
            func_handleRecycling,
            func_del_data,
            func_rec_data,
            func_view_data,
            func_unview_data,
            func_handleEdit,
            func_handleDrawerOpen,            
            func_handleDrawerClose,
            func_drawer_tabsClick,
            func_dialog_saveEdit,
            func_setLevelEditView,
            func_dialog_chooseOptionData,
            func_table_lazy_load,
        };
    },
});
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}
.handle-switch {
    width: 180px;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-input {
    width: 350px;
}
</style>